package com.zkthink.ceres.promotion.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkthink.base.R;
import com.zkthink.base.request.PageParams;
import com.zkthink.base.service.SuperServiceImpl;
import com.zkthink.ceres.common.enums.YesOrNoEnum;
import com.zkthink.ceres.common.event.TenantCreatedEvent;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.event.LoginEvent;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.promotion.dao.SalesCustomerMapper;
import com.zkthink.ceres.promotion.dao.SalesLevelMapper;
import com.zkthink.ceres.promotion.dao.SalesMapper;
import com.zkthink.ceres.promotion.dao.SalesOrderMapper;
import com.zkthink.ceres.promotion.dto.SalesApplyDTO;
import com.zkthink.ceres.promotion.dto.SalesPageDTO;
import com.zkthink.ceres.promotion.dto.SalesUpdateDTO;
import com.zkthink.ceres.promotion.entity.Sales;
import com.zkthink.ceres.promotion.entity.SalesCustomer;
import com.zkthink.ceres.promotion.entity.SalesLevel;
import com.zkthink.ceres.promotion.entity.SalesOrder;
import com.zkthink.ceres.promotion.entity.SalesPromConfig;
import com.zkthink.ceres.promotion.entity.SalesRelationConfig;
import com.zkthink.ceres.promotion.enums.SalesAuditStatusEnum;
import com.zkthink.ceres.promotion.enums.SalesCommissionTypeEnum;
import com.zkthink.ceres.promotion.enums.SalesOrderSettleStatusEnum;
import com.zkthink.ceres.promotion.service.SalesCustomerService;
import com.zkthink.ceres.promotion.service.SalesLevelService;
import com.zkthink.ceres.promotion.service.SalesPromConfigService;
import com.zkthink.ceres.promotion.service.SalesRelationConfigService;
import com.zkthink.ceres.promotion.service.SalesService;
import com.zkthink.ceres.promotion.vo.admin.SalesAdminPageVO;
import com.zkthink.ceres.promotion.vo.admin.SalesOrderPageVO;
import com.zkthink.ceres.promotion.vo.admin.SalesPerformanceAdminVO;
import com.zkthink.ceres.promotion.vo.admin.SalesPerformanceDetailAdminVO;
import com.zkthink.ceres.promotion.vo.web.SalesCustomerVO;
import com.zkthink.ceres.promotion.vo.web.SalesMainInfoVO;
import com.zkthink.ceres.promotion.vo.web.SalesStoreVO;
import com.zkthink.ceres.promotion.vo.web.SubordinateSalesVO;
import com.zkthink.ceres.store.entity.Store;
import com.zkthink.ceres.store.service.StoreService;
import com.zkthink.context.BaseContextHandler;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.dozer.DozerUtils;
import com.zkthink.exception.BizException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 业务实现类 分销员
 * </p>
 *
 * @author kellen
 * @date 2020-08-22
 */
@Slf4j
@Service
@AllArgsConstructor
public class SalesServiceImpl extends SuperServiceImpl<SalesMapper, Sales> implements SalesService {

  private SalesCustomerService salesCustomerService;

  private SalesRelationConfigService relationConfigService;

  private StoreService storeService;

  private SalesLevelMapper salesLevelMapper;

  private SalesOrderMapper salesOrderMapper;

  private MemberService memberService;

  private SalesCustomerMapper salesCustomerMapper;

  private DozerUtils dozerUtils;

  private SalesLevelService salesLevelService;

  private SalesPromConfigService salesPromConfigService;

  private SalesRelationConfigService salesRelationConfigService;

  //private OrderProductService orderProductService;

  @Override
  public IPage<SalesAdminPageVO> page(PageParams<SalesPageDTO> params) {
    SalesPageDTO pageDTO = params.getModel();
    pageDTO.setTenantCode(BaseContextHandler.getTenant());
    return this.baseMapper.page(params.getPage(), pageDTO);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public R quit(Long salesId) {
    Sales sales = this.getById(salesId);
    if (null == sales) {
      return R.validFail("分销员不存在");
    }
    this.removeById(salesId);
    //删除会员绑定关系
    salesCustomerService.update(new SalesCustomer().setSid(0L),
        Wraps.<SalesCustomer>lbU().eq(SalesCustomer::getSid, salesId));
    //删除上下级关系
    this.update(new Sales().setPid(0L), Wraps.<Sales>lbU().eq(Sales::getPid, salesId));
    return R.success();
  }

  @Override
  public R updateSales(SalesUpdateDTO updateDTO) {
    //查询分销员是否存在
    Sales sales = this.getById(updateDTO.getId());
    if (null == sales) {
      return R.validFail("分销员不存在");
    }
    sales.setLevelId(updateDTO.getLevelId());
    sales.setPid(updateDTO.getPid());
    this.updateById(sales);
    return R.success();
  }

  @Override
  public IPage<SalesPerformanceAdminVO> querySalesPerformance(PageParams<SalesPageDTO> params) {
    SalesPageDTO pageDTO = params.getModel();
    pageDTO.setTenantCode(BaseContextHandler.getTenant());
    return this.baseMapper.querySalesPerformance(params.getPage(), pageDTO);
  }

  @Override
  public SalesPerformanceDetailAdminVO querySalesPerformanceDetail(Long salesId) {
    return baseMapper.querySalesPerformanceDetail(salesId, BaseContextHandler.getTenant());
  }

  @Override
  public Sales queryByMidAndTenantCode(Long mid, String tenantCode) {
    return this
        .getOne(Wraps.<Sales>lbQ()
            .eq(Sales::getMid, mid)
            .eq(Sales::getTenantCode, tenantCode));
  }

  @Override
  public void saveSales(SalesApplyDTO salesApplyDTO) {
    SalesLevel salesLevel = salesLevelService.queryStoreDefaultLevel(salesApplyDTO.getTenantCode());
    if (null == salesLevel) {
      throw new BizException("商家分销员等级未设置");
    }

    if (salesApplyDTO.getInviteId() != null && salesApplyDTO.getInviteId() > 0) {
      Sales inviteSales = this.getOne(Wraps.<Sales>lbQ().eq(Sales::getInviteId, salesApplyDTO.getInviteId()));
      if (inviteSales == null) {
        throw new BizException("邀请码不正确");
      }
      if (!inviteSales.getTenantCode().equals(salesApplyDTO.getTenantCode())) {
        throw new BizException("邀请码对应的商家和申请的商家不一致");
      }
      salesApplyDTO.setPid(inviteSales.getId());
    }

    //查询分销相关配置
    SalesRelationConfig salesRelationConfig = salesRelationConfigService.queryByTenantCode(salesApplyDTO.getTenantCode());
    Integer auditStatus = SalesAuditStatusEnum.WAIT_AUDIT.getCode();
    if(salesRelationConfig != null && salesRelationConfig.getAuditFlag() == 1){
      auditStatus = SalesAuditStatusEnum.PASS.getCode();
    }

    //如果设置了申请条件 为至少下单满x元，或消费金额满y元，需要判断是否满足相应的条件
    if(salesRelationConfig != null){
      if(salesRelationConfig.getApplyCondition() == 2
              && salesRelationConfig.getApplyDetail() != null
              && salesApplyDTO.getPayOrderCount() < salesRelationConfig.getApplyDetail() ){
        throw new BizException("下单数不符合申请条件");
      }
      if(salesRelationConfig.getApplyCondition() == 3
              && salesRelationConfig.getApplyDetail() != null
              && salesApplyDTO.getOrderSum() < salesRelationConfig.getApplyDetail() ){
        throw new BizException("累计消费金额不符合申请条件");
      }
    }

    Integer inviteId = (int)(System.currentTimeMillis() % 1000000000);
    Sales sales = Sales.builder()
        .auditStatus(auditStatus)
        .levelId(salesLevel.getId())
        .mobile(salesApplyDTO.getMobile())
        .mid(salesApplyDTO.getMid())
        .pid(salesApplyDTO.getPid())
        .tenantCode(salesApplyDTO.getTenantCode())
        .inviteId(inviteId)
        .build();
    this.save(sales);

    //判断是否开启自购分佣，如果是，分销员和自己绑定关系
    if(salesRelationConfig != null){
      if (salesRelationConfig.getSelfBuyReturnCommisionFlag() == 1) {
        SalesCustomer salesCustomer = SalesCustomer.builder()
                .mid(salesApplyDTO.getMid())
                .isValid(YesOrNoEnum.YES.getCode())
                .tenantCode(salesApplyDTO.getTenantCode())
                .sid(sales.getId()).build();
        salesCustomerMapper.insert(salesCustomer);
      }
    }
  }

  @Override
  public IPage<SalesStoreVO> findSaleStoreList(Long mid, PageParams<Sales> pageParams) {
    if (mid == null || mid <= 0) {
      return null;
    }
    IPage<Sales> salesPage = baseMapper.selectPage(pageParams.getPage(),
        Wraps.<Sales>lbQ().eq(Sales::getMid, mid).eq(Sales::getIsDelete, 0)
            .orderByDesc(Sales::getIsValid).orderByDesc(Sales::getCreateTime));
    List<SalesStoreVO> salesStoreVOList = new ArrayList<SalesStoreVO>();
    for (Sales sales : salesPage.getRecords()) {
      SalesStoreVO salesStoreVO = new SalesStoreVO();
      salesStoreVO.setTenantCode(sales.getTenantCode());
      Store store = storeService.findByTenantCode(sales.getTenantCode());
      if (store != null) {
        salesStoreVO.setStoreName(store.getStoreName());
        salesStoreVO.setLogo(store.getLogo());
      }

      SalesLevel salesLevel = salesLevelMapper.selectById(sales.getLevelId());
      if (salesLevel != null) {
        salesStoreVO.setLevelName(salesLevel.getLevelName());
      }
      salesStoreVO.setIsValid(sales.getIsValid());
      Long orderSum = salesOrderMapper
          .selectCommissionSumByProfitSidAndTenantCode(sales.getId(), sales.getTenantCode(), null, null);
      salesStoreVO.setCommission(orderSum);
      salesStoreVOList.add(salesStoreVO);
    }
    IPage<SalesStoreVO> resultPage = new Page<SalesStoreVO>();
    resultPage.setCurrent(salesPage.getCurrent());
    resultPage.setPages(salesPage.getPages());
    resultPage.setSize(salesPage.getSize());
    resultPage.setTotal(salesPage.getTotal());
    resultPage.setRecords(salesStoreVOList);
    return resultPage;
  }

  @Override
  public SalesMainInfoVO querySalesMainInfo(Long mid, String tenantCode) {
    if (mid == null || mid <= 0 || StringUtils.isBlank(tenantCode)) {
      return null;
    }
    Sales sales = baseMapper
        .selectOne(Wraps.<Sales>lbQ().eq(Sales::getMid, mid).eq(Sales::getTenantCode, tenantCode));
    if (sales != null) {
      SalesMainInfoVO salesMainInfoVO = new SalesMainInfoVO();
      salesMainInfoVO.setSalesId(sales.getId());
      Member member = memberService.findById(mid);
      Store store = storeService.findByTenantCode(tenantCode);
      SalesLevel salesLevel = salesLevelMapper.selectById(sales.getLevelId());
      Long directCommission = salesOrderMapper
          .selectCommissionSumByProfitSidAndTenantCode(sales.getId(), sales.getTenantCode(), null, SalesCommissionTypeEnum.DIRECT.getCode());
      Long indirectCommission = salesOrderMapper
              .selectCommissionSumByProfitSidAndTenantCode(sales.getId(), sales.getTenantCode(), null, SalesCommissionTypeEnum.IN_DIRECT.getCode());
      Long unsettledDirectCommission = salesOrderMapper
          .selectCommissionSumByProfitSidAndTenantCode(sales.getId(), sales.getTenantCode(), SalesOrderSettleStatusEnum.SETTLED.getCode(), SalesCommissionTypeEnum.DIRECT.getCode());
      Long unsettledIndirectCommission = salesOrderMapper
              .selectCommissionSumByProfitSidAndTenantCode(sales.getId(), sales.getTenantCode(), SalesOrderSettleStatusEnum.SETTLED.getCode(), SalesCommissionTypeEnum.IN_DIRECT.getCode());
      Integer accumulativeCustomCount = salesCustomerMapper.selectCustomCount(sales.getId(), tenantCode);
      Integer accumulativeSalesCount = baseMapper.selectSubordinateSalesCount(sales.getId(), tenantCode);
      if (member == null || store == null || salesLevel == null) {
        return null;
      }
      salesMainInfoVO.setTenantCode(tenantCode);
      salesMainInfoVO.setStoreId(store.getId());
      salesMainInfoVO.setDirectRate(salesLevel.getDirectRate());
      salesMainInfoVO.setIndirectRate(salesLevel.getIndirectRate());
      salesMainInfoVO.setNickName(member.getNickname());
      salesMainInfoVO.setRemark(member.getRemark());
      salesMainInfoVO.setHeadimg(member.getHeadimg());
      salesMainInfoVO.setInviteId(sales.getInviteId());
      salesMainInfoVO.setDirectCommission(directCommission);
      salesMainInfoVO.setIndirectCommission(indirectCommission);
      salesMainInfoVO.setCommission(directCommission + indirectCommission);
      salesMainInfoVO.setUnsettledCommission(unsettledDirectCommission+unsettledIndirectCommission);
      salesMainInfoVO.setUnsettledDirectCommission(unsettledDirectCommission);
      salesMainInfoVO.setUnsettledIndirectCommission(unsettledIndirectCommission);
      salesMainInfoVO.setAccumulativeCustomCount(accumulativeCustomCount);
      salesMainInfoVO.setAccumulateSalesCount(accumulativeSalesCount);
      return salesMainInfoVO;
    }
    return null;
  }

  @Override
  public IPage<SalesOrderPageVO> findSalesOrderPage(PageParams<SalesOrder> pageParams) {
    if (pageParams != null) {
      Long saleMid = pageParams.getModel().getMid();
      String tenantCode = pageParams.getModel().getTenantCode();
      Integer type = pageParams.getModel().getType();
      Integer settleStatus = pageParams.getModel().getSettleStatus();
      Sales sales = baseMapper.selectOne(Wraps.<Sales>lbQ().eq(Sales::getMid,saleMid)
                                              .eq(Sales::getTenantCode,tenantCode)
                                              .eq(Sales::getIsDelete, YesOrNoEnum.NO.getCode()));
      if(sales != null){
        IPage<SalesOrder> salesOrderPage = salesOrderMapper
                .selectPage(pageParams.getPage(), Wraps.<SalesOrder>lbQ()
                        .eq(SalesOrder::getProfitSid, sales.getId())
                        .eq(SalesOrder::getTenantCode, pageParams.getModel().getTenantCode())
                        .eq(SalesOrder::getIsDelete, 0).orderByDesc(SalesOrder::getCreateTime)
                        .eq(type!=null,SalesOrder::getType,type)
                        .eq(settleStatus!=null,SalesOrder::getSettleStatus,settleStatus));
        List<SalesOrderPageVO> salesOrderPageVOList = new ArrayList<>();
        for (SalesOrder salesOrder : salesOrderPage.getRecords()) {
          Long mid = salesOrder.getMid();
          Member member = memberService.getById(mid);
          SalesOrderPageVO salesOrderPageVO = new SalesOrderPageVO();
          dozerUtils.map(salesOrder, salesOrderPageVO);
          salesOrderPageVO.setNickname(member.getNickname());

          //如果是间接奖励，需要查出相应的分销员的昵称
          if(salesOrder.getType() == SalesCommissionTypeEnum.IN_DIRECT.getCode()){
            Long profitSid = salesOrder.getProfitSid();
            if(profitSid != null){
              Member profitMember = memberService.getById(mid);
              if(profitMember != null){
                salesOrderPageVO.setSalesName(profitMember.getNickname());
              }
            }
          }

          //设置显示控制字段
          Map<String,Object> displayControlMap = new HashMap<String,Object>();
          displayControlMap.put("nickname",member.getNickname());
          displayControlMap.put("orderAmount",salesOrder.getOrderAmount());
          displayControlMap.put("settleStatus",salesOrder.getSettleStatus());
          displayControlMap.put("salesName",salesOrderPageVO.getSalesName());

          salesOrderPageVO.setDisplayControlMap(displayControlMap);
          salesOrderPageVOList.add(salesOrderPageVO);
        }

        IPage<SalesOrderPageVO> resultPage = new Page<>();
        resultPage.setCurrent(salesOrderPage.getCurrent());
        resultPage.setPages(salesOrderPage.getPages());
        resultPage.setSize(salesOrderPage.getSize());
        resultPage.setTotal(salesOrderPage.getTotal());
        resultPage.setRecords(salesOrderPageVOList);
        return resultPage;
      }
    }
    return null;
  }

  @Override
  public IPage<SalesCustomerVO> findSalesCustomerList(PageParams<SalesCustomer> pageParams) {
    if (pageParams != null) {
      Long saleMid = pageParams.getModel().getMid();
      String tenantCode = pageParams.getModel().getTenantCode();
      Sales sales = baseMapper.selectOne(Wraps.<Sales>lbQ().eq(Sales::getMid,saleMid)
              .eq(Sales::getTenantCode,tenantCode)
              .eq(Sales::getIsDelete, YesOrNoEnum.NO.getCode()));
      if(sales != null){
        IPage<SalesCustomer> customerPage = salesCustomerMapper.selectPage(pageParams.getPage(),
                Wraps.<SalesCustomer>lbQ().eq(SalesCustomer::getSid, sales.getId())
                        .eq(SalesCustomer::getTenantCode, tenantCode)
                        .eq(SalesCustomer::getIsDelete, 0));
        List<SalesCustomerVO> salesCustomerVOList = new ArrayList<>();
        for (SalesCustomer salesCustomer : customerPage.getRecords()) {
          SalesCustomerVO customerVO = new SalesCustomerVO();
          customerVO.setMid(salesCustomer.getMid());
          Member member = memberService.findById(salesCustomer.getMid());
          if (member != null) {
            customerVO.setNickName(member.getNickname());
            customerVO.setPhone(member.getPhone());
            Integer accumulativeOrderCount = salesOrderMapper.selectCount(Wraps.<SalesOrder>lbQ()
                    .eq(SalesOrder::getMid, salesCustomer.getMid())
                    .eq(SalesOrder::getSid, salesCustomer.getSid())
                    .eq(SalesOrder::getTenantCode, salesCustomer.getTenantCode()));
            customerVO.setAccumulativeOrderCount(accumulativeOrderCount);

            Long accumulativeOrderSum = salesOrderMapper
                    .selectOrderSumByMidAndSidAndTenantCode(salesCustomer.getMid(), salesCustomer.getSid(),
                            salesCustomer.getTenantCode());
            customerVO.setAccumulativeOrderSum(accumulativeOrderSum);
            //设置显示控制字段
            Map<String,Object> displayControlMap = new HashMap<String,Object>();
            displayControlMap.put("accumulativeOrderCount",accumulativeOrderCount);
            displayControlMap.put("accumulativeOrderSum",accumulativeOrderSum);
            customerVO.setDisplayControlMap(displayControlMap);
            salesCustomerVOList.add(customerVO);
          }
        }
        IPage<SalesCustomerVO> resultPage = new Page<>();
        resultPage.setCurrent(customerPage.getCurrent());
        resultPage.setPages(customerPage.getPages());
        resultPage.setSize(customerPage.getSize());
        resultPage.setTotal(customerPage.getTotal());
        resultPage.setRecords(salesCustomerVOList);
        return resultPage;
      }
    }
    return null;
  }

  @Override
  public IPage<SubordinateSalesVO> findSubordinateSalesList(PageParams<Sales> pageParams) {
    if (pageParams == null || pageParams.getModel() == null
        || pageParams.getModel().getMid() == null
        || pageParams.getModel().getMid() <= 0 || StringUtils
        .isBlank(pageParams.getModel().getTenantCode())) {
      return null;
    }

    Long saleMid = pageParams.getModel().getMid();
    String tenantCode = pageParams.getModel().getTenantCode();
    Sales curSales = baseMapper.selectOne(Wraps.<Sales>lbQ().eq(Sales::getMid,saleMid)
            .eq(Sales::getTenantCode,tenantCode)
            .eq(Sales::getIsDelete, YesOrNoEnum.NO.getCode()));
    if(curSales != null){
      IPage<Sales> salesPage = baseMapper
              .selectPage(pageParams.getPage(), Wraps.<Sales>lbQ().eq(Sales::getPid, curSales.getId())
                      .eq(Sales::getTenantCode, tenantCode)
                      .eq(Sales::getIsDelete, 0));
      List<SubordinateSalesVO> subordinateSalesVOList = new ArrayList<>();
      for (Sales sales : salesPage.getRecords()) {
        SubordinateSalesVO salesVO = new SubordinateSalesVO();
        Member member = memberService.findById(sales.getMid());
        salesVO.setNickname(member.getNickname());
        salesVO.setPhone(member.getPhone());
        Integer accumulativeOrderCount = salesOrderMapper.selectCount(Wraps.<SalesOrder>lbQ()
                .eq(SalesOrder::getMid, sales.getMid())
                .eq(SalesOrder::getTenantCode, sales.getTenantCode()));
        salesVO.setAccumulativeOrderCount(accumulativeOrderCount);

        Long indirectCommission = salesOrderMapper
                .selectIndirectCommission(sales.getId(), curSales.getId(), tenantCode);
        salesVO.setIndirectCommission(indirectCommission);
        //设置显示控制字段
        Map<String,Object> displayControlMap = new HashMap<String,Object>();
        displayControlMap.put("accumulativeOrderCount",accumulativeOrderCount);
        displayControlMap.put("indirectCommission",indirectCommission);
        salesVO.setDisplayControlMap(displayControlMap);
        subordinateSalesVOList.add(salesVO);
      }
      IPage<SubordinateSalesVO> resultPage = new Page<>();
      resultPage.setCurrent(salesPage.getCurrent());
      resultPage.setPages(salesPage.getPages());
      resultPage.setSize(salesPage.getSize());
      resultPage.setTotal(salesPage.getTotal());
      resultPage.setRecords(subordinateSalesVOList);
      return resultPage;
    }
    return null;
  }

  @Override
  public IPage<SalesOrderPageVO> findMySalesPage(PageParams<SalesOrder> pageParams) {
    if (pageParams == null || pageParams.getModel() == null
        || pageParams.getModel().getMid() == null
        || pageParams.getModel().getMid() <= 0 || StringUtils
        .isBlank(pageParams.getModel().getTenantCode())) {
      return null;
    }
    Long saleMid = pageParams.getModel().getMid();
    String tenantCode = pageParams.getModel().getTenantCode();
    Sales curSales = baseMapper.selectOne(Wraps.<Sales>lbQ().eq(Sales::getMid,saleMid)
            .eq(Sales::getTenantCode,tenantCode)
            .eq(Sales::getIsDelete, YesOrNoEnum.NO.getCode()));

    IPage<SalesOrderPageVO> resultPage = new Page<>();

    if(curSales != null){
      IPage<SalesOrder> salesOrderPage = salesOrderMapper
              .selectPage(pageParams.getPage(), Wraps.<SalesOrder>lbQ().eq(SalesOrder::getSid, curSales.getId())
                      .eq(SalesOrder::getTenantCode, tenantCode)
                      .eq(SalesOrder::getIsDelete, 0).orderByDesc(SalesOrder::getCreateTime));
      List<SalesOrderPageVO> salesOrderPageVOList = new ArrayList<>();
      for (SalesOrder salesOrder : salesOrderPage.getRecords()) {
        SalesOrderPageVO salesOrderPageVO = new SalesOrderPageVO();
        dozerUtils.map(salesOrder, salesOrderPageVO);

        Member member = memberService.findById(salesOrder.getMid());
        salesOrderPageVO.setNickname(member.getNickname());
        //设置显示控制字段
        Map<String,Object> displayControlMap = new HashMap<String,Object>();
        displayControlMap.put("orderAmount",salesOrder.getOrderAmount());
        displayControlMap.put("nickname",member.getNickname());
        displayControlMap.put("settleStatus",salesOrderPageVO.getSettleStatus());
        salesOrderPageVO.setDisplayControlMap(displayControlMap);
        salesOrderPageVOList.add(salesOrderPageVO);
      }

      resultPage.setCurrent(salesOrderPage.getCurrent());
      resultPage.setPages(salesOrderPage.getPages());
      resultPage.setSize(salesOrderPage.getSize());
      resultPage.setTotal(salesOrderPage.getTotal());
      resultPage.setRecords(salesOrderPageVOList);
    }

    return resultPage;
  }

  /**
   * 监听登录事件,绑定客户和分销员关系
   */
  @EventListener
  @Async
  public void handleBindCustomer(LoginEvent event) {
    log.info("监听到登录成功事件:{}", event);
    if (null == event.getSalesId()) {
      log.warn("分销员id为空，不处理分销员绑定");
      return;
    }
    Sales sales = this.getById(event.getSalesId());
    if(sales == null){
      return;
    }
    //查询当前店铺的配置信息
    SalesRelationConfig config = relationConfigService.queryByTenantCode(sales.getTenantCode());
    //判断客户是否是本店铺的分销员
/*    Sales sales = this.getOne(Wraps.<Sales>lbQ()
        .eq(Sales::getTenantCode, event.getTenantCode())
        .eq(Sales::getMid, event.getMid()));*/
    SalesCustomer salesCustomer = salesCustomerService
        .getOne(Wraps.<SalesCustomer>lbQ()
            .eq(SalesCustomer::getMid, event.getMid())
            .gt(SalesCustomer::getTenantCode, sales.getTenantCode()));
    if (sales != null) {
      //是否允许分销员之前绑定客户关系
      if (null != config) {
        if (1 == config.getSalesBindFalg()) {
          //查询当前客户是否有被同店铺的分销员绑定
          if (salesCustomer != null) {
            //是否允许抢客，随时允许
            if (1 == config.getRebindCustomerFlag()) {
              //更新绑定关系
              salesCustomer.setSid(event.getSalesId());
              salesCustomerService.updateById(salesCustomer);
            }
          }
        }
      }
    }
    //不是分销员身份
    //查询当前客户是否有被同店铺的分销员绑定
    if (salesCustomer != null) {
      //是否允许抢客，随时允许
      if (null != config && 1 == config.getRebindCustomerFlag()) {
        //更新绑定关系
        salesCustomer.setSid(event.getSalesId());
        salesCustomerService.updateById(salesCustomer);
      }
    } else {
      //初始绑定
      salesCustomer = SalesCustomer.builder()
          .mid(event.getMid())
          .tenantCode(sales.getTenantCode())
          .sid(event.getSalesId()).build();
      salesCustomerService.save(salesCustomer);
    }
  }

  @EventListener
  @Async
  public void handleTenantCreated(TenantCreatedEvent event) {
    BaseContextHandler.setTenant(event.getTenantCode());
    //salesLevelService.save(SalesLevel.builder().isDefault(1).build());
    salesPromConfigService.save(SalesPromConfig.builder().type(1).isShowShopLogo(1).isShowNickName(1).build());
    salesPromConfigService.save(SalesPromConfig.builder().type(2).isShowShopLogo(1).isShowNickName(1).build());
    salesRelationConfigService.save(SalesRelationConfig.builder().isForeverValid(YesOrNoEnum.YES.getCode()).protectTime(30)
            .rebindCustomerFlag(2).salesBindFalg(1).selfBuyReturnCommisionFlag(2).build());
  }

}
